﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace SipII
{
    class LogWritor
    {
        //日志队列
        private Queue<string> logQueue;

        /// <summary>
        /// 实例化函数
        /// </summary>
        public LogWritor()
        {
            logQueue = new Queue<string>() { };
        }

        /// <summary>
        /// 输出日志
        /// </summary>
        /// <param name="log"></param>
        public void Output(string log)
        {
            log = string.Format("{0}\t{1}", DateTime.Now, log);

            Console.WriteLine(log);

            lock (logQueue)
            {
                if (logQueue.Count < Properties.Settings.Default.LogQueneLength)
                {
                    logQueue.Enqueue(log);
                }
                else
                {
                    Clear();
                }
            }
        }

        /// <summary>
        /// 清空日志
        /// </summary>
        public void Clear()
        {
            Object thisLock = new Object();

            lock (thisLock)
            {
                StreamWriter sw = new StreamWriter("log.txt", true, Encoding.UTF8);

                while (logQueue.Count > 0)
                {
                    sw.WriteLine(logQueue.Dequeue());
                }

                sw.Close();
            }
        }
    }
}
